package com.xinglong.spider.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Author：胡云峰
 * @Date：2022/12/7 10:56
 */
public class BaiDuOcrUtils {

    /**
     * @ author 胡云峰
     * 获取   access token
     * 注意： access_token的有效期为30天，需要每30天进行定期更换；
     */
    public static String getAccessToken(){
        //向https://aip.baidubce.com/oauth/2.0/token发送请求
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        //设置contentType格式
        String contentType = "application/x-www-form-urlencoded";
        // 固定值为client_credentials
        String grant_type = "client_credentials";
        //应用的 API Key
        String client_id = "oOfYUwPZ3xTerx6ftrzxm5CP";
        //应用的 Secret Key
        String client_secret = "Uw201eojRbom9zuDpKwfSfjWwmd31ZEg";
        //参数
        String para = "grant_type="+grant_type+"&client_id="+client_id+"&client_secret=" + client_secret;
        //发起post请求
        String resp = HttpUtils.sendPost(url, para, contentType);
        //解析返回信息获取access_token
        JSONObject jsonObject = JSONObject.parseObject(resp);
        return jsonObject.get("access_token").toString();
    }

    /**
     * 获取图片文字信息
     * @return
     */
    public static String getOcrMessage(String imgStr){
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic" + "?access_token=" +getAccessToken();
        //设置contentType格式
        String contentType = "application/x-www-form-urlencoded";
        //注意：一定要urlencoder，否则会出现图片格式不对的报错
        try {
            imgStr = URLEncoder.encode(imgStr, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //发起请求
        String resp = HttpUtils.sendPost(url, "image=" + imgStr, contentType);
        //利用阿里的fastjson解析
        JSONObject jsonObject = JSONObject.parseObject(resp);
        String wordsResult = jsonObject.get("words_result").toString();
        //words_result是一个集合
        JSONArray jsonArray = JSONArray.parseArray(wordsResult);
        //组装解析后的结果
        StringBuilder sb = new StringBuilder();
        for (Object o : jsonArray) {
            //Object强转成JSONObject
            JSONObject jObject = (JSONObject) o;
            //解析words
            String words = jObject.get("words").toString();
            //组装到sb
            sb.append(words);
        }
        //返回结果
        return sb.toString();
    }

    public static void main(String[] args) {
        //image base64
//        String imgStr = "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA8AKADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDtrW1ga1hZoIySikkoOeKsCztv+feL/vgU2z/484P+ua/yqyKiMY8q0IjGPKtCIWdr/wA+0P8A3wKeLK1/59of+/YqUU7IHWnyx7D5Y9iIWVp/z6w/9+xThY2n/PrB/wB+xWb/AM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HSvR7e1QRjKijNMZDGYl16asnbTTf5b+oQi4qzOK1mwvV0iQ6ZKttd5L/dG2Q993v715Tf3uuXNs9jd2TGXOGkKEEj+X419Bahp/nRkKK5S48LyTS8g4zVYLMVhlZ0oyad03un6rdeQShzdTz3wxpFwtnc291FuhnGClXrPwVbQ3IdYXkIPHmHIH4V6bpXhpIFAZa3YdHhQ52ipr5piqtSc+bl590rpMFCKVjk9E0eVMCRcqeCCODXWXNpm0IxzitGK1SMcKKmaIMmMV5xZ4V4r0nXbfU4bjRC+A+54o9q/NnOT03Z7g+nvXrfhHURqejQztA9vPjbNC64aNx1HP5g9wQe9R32jebLvUVp6ZamBQCOeldVTE+0oxpOKvHqtG79+/kSo2dzWFPFNXpTxXKUOFVdX/AOQJf/8AXtJ/6Catiqur/wDIEv8A/r2k/wDQTUy+Fky+FnJWX/Hlb/8AXNf5VZFczFrVzFEkapEQihRkHt+NSf2/df8APOH/AL5P+NZRrRsjONWNkdKKcK5n/hIbv/nnB/3yf8aX/hIrv/nnB/3yf8ar20R+2idQBQ0YcYIrmP8AhJLz/nlB/wB8n/Gl/wCElvP+eUH/AHyf8aPbRD20To0tEVshRVtVwK5L/hJ73/nlb/8AfLf40v8AwlF7/wA8rf8A75b/ABo9tEPbROv2g0CFc5wK5H/hKr7/AJ5W/wD3y3+NL/wld9/zytv++W/xo9tEPbROxVAOgqUCuK/4S2//AOeNt/3y3+NL/wAJfqH/ADxtv++W/wDiqPbRD20TthTxXD/8JhqH/PG1/wC+W/8AiqX/AITLUf8Anja/98t/8VR7aIe2idzsB7U5UArhf+Ez1H/nja/98N/8VS/8JrqX/PC0/wC+G/8AiqPbRD20TvRTxXAf8JtqX/PC0/74b/4ql/4TjU/+eFp/3w3/AMVR7aIe2iegiqur/wDID1D/AK9pP/QTXFf8Jzqf/PC0/wC+G/8AiqjufGeo3VrNbvDahJUZGKq2QCMcfNUyrRsxSqxsz//Z";
        String ocrMessage = getOcrMessage(testImg);
        System.out.println(ocrMessage);
    }

}
